/*
 * QTXpost - a Qt-based blog client.
 * Copyright (C) 2010 Helen Sommer
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; version 3 of the License.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program (in COPYING); if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 * MA  02111-1307  USA
 *
 * The project is hosted on http://code.google.com/p/qtxpost
 */

#include <QtDebug>

#include "Communities.h"
#include "Server.h"
#include "Config.h"

extern Config *config;

Communities::Communities(Server *server_,QWidget *parent)
  : QDialog(parent)
{
  setupUi(this);

  server = server_;
  groupMask = 0;

  connect(okButton, SIGNAL(clicked()), this, SLOT(close()));

  communitiesLayout = new QVBoxLayout();
  communitiesLayout->setContentsMargins(4, 4, 4, 4);
  communitiesForm->setLayout(communitiesLayout);

  groupsLayout = new QVBoxLayout();
  groupsLayout->setContentsMargins(4, 4, 4, 4);
  groupsForm->setLayout(groupsLayout);
}

void Communities::readCommunities()
{
  QSqlQuery query;
  QString command;

  if (!config->settings.value("save_communities_crossposting").toBool()) {
    command = QString("update communities set selected=0 where users_id=%1").arg(server->id);
    query.exec(command);
  }

  command = QString("select community,selected from communities where users_id=%1 order by type desc,community asc").arg(server->id);
  query.exec(command);
  while (query.next()) {
   QString community = query.value(0).toString();
   bool selected = query.value(1).toBool();
   QCheckBox *name = new QCheckBox(community, communitiesForm);
   connect(name, SIGNAL(stateChanged(int)), this, SLOT(toggleCommunity(int)));
   communitiesLayout->addWidget(name, 1);
   communities.append(name);
   if (selected) {
     name->setChecked(true);
   }
  }
  communitiesLayout->insertStretch(-1,2); 
  server->renameCommunitiesButton(getTitle());
}

void Communities::readGroups()
{
  QSqlQuery query;
  QString command;

  groupMask = 0;
  command = QString("select name,selected,bit from groups where users_id=%1 and type=0 order by sortorder").arg(server->id);
  query.exec(command);
  while (query.next()) {
   QString group = query.value(0).toString();
   bool selected = query.value(1).toBool();
   qulonglong bit = query.value(2).toULongLong();
   QCheckBox *name = new QCheckBox(group, groupsForm);
   groupsLayout->addWidget(name, 1);
   groups.append(name);
   if (selected && config->settings.value("save_custom_groups").toBool()) {
     groupMask |= (1 << bit);
     name->setChecked(true);
   }
  }
  groupsLayout->insertStretch(-1,2); 
}

void Communities::updateCommunities()
{
  QSqlQuery query;
  QString command;
  QStringList checked;

  //remove all items from layout
  QLayoutItem *child;
  while ((child = communitiesLayout->takeAt(0)) != 0) { }
  
  for (int i = 0; i < communities.size(); i++) {
    QCheckBox *name = communities.at(i);
    if (name->isChecked()){
      checked.append(name->text());
    }
    communitiesLayout->removeWidget(name);
    name->deleteLater();
  }
  communities.clear();

  command = QString("select community from communities where users_id=%1 order by type desc, community asc").arg(server->id);
  query.exec(command);
  while (query.next()) {
   QString community = query.value(0).toString();
   QCheckBox *name = new QCheckBox(community, communitiesForm);
   connect(name, SIGNAL(stateChanged(int)), this, SLOT(toggleCommunity(int)));
   communitiesLayout->addWidget(name, 1);
   communities.append(name);
   if (checked.contains(community)){
     name->setChecked(true);
   }
  }
  communitiesLayout->insertStretch(-1,2); 
}

void Communities::updateGroups()
{
  QSqlQuery query;
  QString command;
  QStringList checked;

  //remove all items from layout
  QLayoutItem *child;
  while ((child = groupsLayout->takeAt(0)) != 0) { }

  for (int i = 0; i < groups.size(); i++) {
    QCheckBox *name = groups.at(i);
    if (name->isChecked()){
      checked.append(name->text());
    }
    groupsLayout->removeWidget(name);
    name->deleteLater();
  }
  groups.clear();

  command = QString("select name from groups where users_id=%1 and type=0 order by sortorder").arg(server->id);
  query.exec(command);
  while (query.next()) {
   QString group = query.value(0).toString();
   QCheckBox *name = new QCheckBox(group, groupsForm);
   groupsLayout->addWidget(name, 1);
   groups.append(name);
   if (checked.contains(group)) {
     name->setChecked(true);
   }
  }
  groupsLayout->insertStretch(-1,2); 
}

QString Communities::getTitle()
{
  int count = 0;
  int first = 0;
  QString text;

  for (int i = 0; i < communities.size(); i++) {
    QCheckBox *name = communities.at(i);
    if (name->isChecked()) {
      count++;
      if (count == 1)
        first = i;
    }
  }

  switch (count) {
  case 0:
    return server->username;
  case 1:
    text = communities.at(first)->text();
    if (text != server->username) {
      return QString("( %1 )").arg(text);
    }
    else {
      return server->username;
    }
    break;
  default:
    text = QString("%1 (%2)").arg(communities.at(first)->text()).arg(count);
    return text;
  }
}

void Communities::toggleCommunity(int)
{
  if (!communitiesForm->isHidden()) {
    server->renameCommunitiesButton(getTitle());
  }
}

void Communities::setGroups(qulonglong mask)
{
  QSqlQuery query;
  QString command;

  for (int i = 0; i < groups.size(); i++) {
    groups.at(i)->setChecked(false);
  }

  for (int k = 1; k < 64; k++) {
    mask >>= 1;
    if ((mask & 1) == 0) continue;
    command = QString("select name from groups where users_id=%1 and type=0 and bit=%2").arg(server->id).arg(k);
    query.exec(command);
    if (query.next()) {
      QString group = query.value(0).toString();
      for (int i = 0; i < groups.size(); i++) {
        if (groups.at(i)->text() == group) {
          groups.at(i)->setChecked(true);
        }
      }
    }
  }
}

void Communities::closeEvent(QCloseEvent *event)
{
  QSqlQuery query;
  QString command;

  command = QString("update communities set selected=0 where users_id=%1").arg(server->id);
  query.exec(command);
  bool checked = false;
  for (int i = 0; i < communities.size(); i++) {
    QCheckBox *name = communities.at(i);
    if (name->isChecked()) {
      checked = true;
      command = QString("update communities set selected=1 where users_id=%1 and community=\"%2\"").arg(server->id).arg(name->text());
      query.exec(command);
    }
  }

  //set the username to be checked if no other communities are selected
  if (!checked) {
    if (communities.size()) {
      communities.at(0)->setChecked(true);
      command = QString("update communities set selected=1 where users_id=%1 and community=\"%2\"").arg(server->id).arg(server->username);
      query.exec(command);
    }
  }

  command = QString("update groups set selected=0 where users_id=%1 and type=0").arg(server->id);
  query.exec(command);
  groupMask = 0;
  qulonglong n = 1;
  for (int i = 0; i < groups.size(); i++) {
    if (!groups.at(i)->isChecked()) continue;
    QString name = groups.at(i)->text();
    command = QString("update groups set selected=1 where users_id=%1 and name=\"%2\" and type=0").arg(server->id).arg(name);
    query.exec(command);
    command = QString("select bit from groups where users_id=%1 and name=\"%2\" and type=0").arg(server->id).arg(name);
    query.exec(command);
    if (query.next()) {
      qulonglong bit = query.value(0).toULongLong();
      groupMask |= (n << bit);
    }
  }
  event->accept();
}
